package com.example.demo.filter;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.example.demo.util.JwtUtil;
import com.google.common.collect.Lists;

/**
 * @author 88377761
 *
 */
@Component
public class LoginGatewayFilterFactory extends AbstractGatewayFilterFactory<LoginGatewayFilterFactory.Config> {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginGatewayFilterFactory.class);

	public LoginGatewayFilterFactory() {
		super(Config.class);
	}


	public static class Config {
		// 控制是否开启认证
		private List<String> passUrl=Lists.newArrayList();

		public List<String> getPassUrl() {
			return passUrl;
		}

		public void setPassUrl(List<String> passUrl) {
			this.passUrl = passUrl;
		}

	}

	/**
	 * @param config
	 * @return create by zy 88377761
	 */
	@Override
	public GatewayFilter apply(Config config) {
		return (exchange, chain) -> {
			URI uri = exchange.getRequest().getURI();
			String path = uri.getPath();
			AntPathMatcher matcher = new AntPathMatcher();
			for(String pattern:config.passUrl) {
				if(matcher.match(pattern,path))
					return chain.filter(exchange);
			}
			ServerHttpRequest request = exchange.getRequest();
			ServerHttpResponse response = exchange.getResponse();
			String token = request.getHeaders().getFirst("token");
			if (StringUtils.isBlank(token)) {
				response.setStatusCode(HttpStatus.UNAUTHORIZED);
				return response.setComplete();
			}
			try {
				if (!JwtUtil.checkJWT(token)) {
					response.setStatusCode(HttpStatus.UNAUTHORIZED);
					return response.setComplete();
				}
			} catch (Exception e) {
				LOGGER.error("校验jwt:", e);
				response.setStatusCode(HttpStatus.UNAUTHORIZED);
				return response.setComplete();
			}
			return chain.filter(exchange);
		};
	}
}
